<template>
	<!-- 资金计划 -->
	<view>
		<u-loading-page bg-color="#fff" :loading="pageLoading" textSize="8"></u-loading-page>
		<view class="container-box" v-if="!pageLoading">
			<view class="pl-30">
				<sub-title>基本信息</sub-title>
			</view>
			<view class="pl-30 pr-30">
				<u--form labelPosition="left" labelWidth="160" :model="formData" class="pl-30 pr-30"
					:labelStyle="{fontSize: '28rpx'}">
					<u-form-item v-for="(item, i) in mapData" :key="i" :label="item.name"
						:borderBottom="item.name!='当月计划收款小于累计应收款说明'" labelWidth="auto">
						<!-- 对象中的对象字段 -->
						<u--input v-if="['合同编号','合同名称'].indexOf(item.name)!=-1" :value="formData.contractInfo[item.label]"
							border="none" inputAlign="right" readonly />
						<u--input v-else-if="['分包商'].indexOf(item.name)!=-1"
							:value="formData.contractInfo.subsupplier[item.label]" border="none" inputAlign="right" readonly />
						<u--input v-else-if="['税率'].indexOf(item.name)!=-1" :value="formData.contractInfo[item.label]"
							border="none" inputAlign="right" readonly />
						<u--input v-else :value="formData[item.label]" border="none" inputAlign="right" readonly />
					</u-form-item>
				</u--form>
			</view>
			<!-- 分包支出/分供支出 -->
			<view v-for="item,index in listData" :key="index">
				<view class="space" />
				<view class="pl-30 pt-30">
					<sub-title>{{index==0?'分包支出':'分供支出'}}</sub-title>
				</view>
				<view class="ml-30 mr-30 mb-30 mt-30 collapse-box">
					<u-collapse accordion :border="false" value="0">
						<u-collapse-item :name="i" title="合同编号" v-for="(ite, i) in item" :key="i" class="mb-20">
							<text slot="value"
								class="u-page__item__title__slot-title">{{index==0?ite.fbContractCode:ite.fgContractCode}}</text>
							<u--form labelPosition="left" labelWidth="80" :labelStyle="{fontSize: '28rpx'}">
								<u-form-item v-for="(it, ind) in column" :label="it.label"
									:borderBottom="ind==column.length-1?false:true"
									v-if="(index==0&&['分供名称'].indexOf(it.label)==-1)||(index==1&&['合同类型','分包名称'].indexOf(it.label)==-1)"
									:key="ind">
									<u--textarea v-if="['合同名称','分包名称'].indexOf(it.label)!=-1" confirmType="done"
										@linechange="handleLineChange(index,i,it,$event)" :autoHeight="true"
										:class="{projectclass: true,oneLine: true}"
										v-model="it.label=='合同名称'?(index==0?ite.fbContractName:ite.fgContractName):ite[it.key]"
										:disabled="true" border="none" />
									<u--input v-else :value="ite[it.key]" border="none" inputAlign="right" readonly />
								</u-form-item>
							</u--form>
						</u-collapse-item>
					</u-collapse>
				</view>
			</view>
			<!-- 资金费用 -->
			<view class="space" />
			<view class="pl-30 pt-30">
				<sub-title v-if="fromTab==0">资金费用</sub-title>
			</view>
			<view class="pl-30 pr-30">
				<u--form labelPosition="left" labelWidth="160" :model="expensesForm" class="pl-30 pr-30"
					:labelStyle="{fontSize: '28rpx'}">
					<u-form-item v-for="(item, i) in mapData2" :key="i" :label="item.name" :borderBottom="item.name!='借款应计息'"
						labelWidth="auto">
						<u--input :value="expensesForm[item.label]" border="none" inputAlign="right" readonly />
					</u-form-item>
				</u--form>
			</view>

			<!-- 资金计划 -->
			<view class="space" />
			<view class="pl-30 pt-30">
				<sub-title v-if="fromTab==0">资金计划</sub-title>
			</view>
			<view class="pl-30 pr-30">
				<u--form labelPosition="left" labelWidth="160" :model="expensesPlan" class="pl-30 pr-30"
					:labelStyle="{fontSize: '28rpx'}">
					<u-form-item v-for="(item, i) in mapData3" :key="i" :label="item.name"
						:borderBottom="item.name!='其中：不可动用部分'" labelWidth="auto"
						:class="{'sub-label': ifSubLabel(item.name)}">
						<u--input :value="expensesPlan[item.label]?expensesPlan[item.label]:'-'" border="none"
							inputAlign="right" readonly />
					</u-form-item>
				</u--form>
			</view>

			<!-- 审批 -->
			<view class="space" v-if="fromTab==0" />
			<view class="pl-30 pt-30">
				<sub-title v-if="fromTab==0">审批</sub-title>
			</view>
			<u--form v-if="fromTab==0" :model="approvalForm" ref="approvalForm" :rules="rules" class="approval-form">
				<view class="pl-30 pt-30 pr-30 pb-30">
					<view class="pb-30 fs-28">审批结果</view>
					<view class="pb-30" style="border-bottom: 1px solid #dee2eb;">
						<u-radio-group v-model="approvalForm.type" @change="groupChange" class="group-text" size="24">
							<u-radio shape="circle" label="通过" name="1" />
							<u-radio :customStyle="{marginLeft: '36rpx',fontSize: '20rpx'}" shape="circle" label="退回" name="2"
								v-if="stepActive !== 1" />
							<u-radio :customStyle="{marginLeft: '36rpx'}" shape="circle" label="驳回" name="3" />
						</u-radio-group>
					</view>
				</view>
				<view class="pl-30 pr-30 pb-30" v-if="approvalForm.type==2">
					<view class="pb-30 fs-28">退回节点</view>
					<view class="pb-30" style="border-bottom: 1px solid #dee2eb;">
						<view @click="nodeInputHandler"
							style="display: flex;align-items: center;font-size: 28rpx;color: #C8CBD2;border: 1rpx solid #EAEAEA;padding: 10rpx;">
							{{approvalForm.returnNodeName||'请选择退回节点'}}
						</view>
					</view>
				</view>
				<view class="pl-30 pr-30 pb-10">
					<view class="pb-30 fs-28">审批意见</view>
					<u--textarea confirmType="done" v-model="approvalForm.comment" maxlength="255" :count="true"
						placeholder="请输入审批意见"></u--textarea>
				</view>
			</u--form>
			<u-picker :show="showPicker" :closeOnClickOverlay="true" :columns="returnsList" @confirm="confirmPicker"
				@close="closePicker" @cancel="closePicker" keyName="name"></u-picker>
			<!-- 审批记录 -->
			<view class="space" />
			<approval-records class="ml-30 mr-30 pt-30" :flowList="flowList" />
			<!-- 提交审批 -->
			<view class="fix-btn" id="fixB" v-if="fromTab==0">
				<u-button type="primary" size="small" text="提交" color="#2289FF" class="btnB fs-28" @click="submitForm"
					:loading="loading"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import SubTitle from '@/pagesIndex/component/SubTitle.vue'
	import InfoCard from '@/pagesIndex/component/InfoCard.vue'
	import FileUpload from '@/components/fileUpload.vue'
	import ApprovalRecords from '@/pagesIndex/contractManagement/approvelRecords.vue'
	export default {
		components: {
			SubTitle,
			FileUpload,
			InfoCard,
			ApprovalRecords
		},
		data() {
			const checkApprovalType = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					callback(new Error('请选择审批结果'))
				}
			}
			const checkApprovalComment = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					callback(new Error('请输入审批意见'))
				}
			}
			const checkApprovalTargetKey = (rule, value, callback) => {
				if (value) {
					callback()
				} else {
					if (this.approvalForm.type != 2) {
						callback()
					} else {
						callback(new Error('请选择退回节点'))
					}
				}
			}
			return {
				linecList: [],
				linecList2: [],
				pageLoading: true,
				screenHeight: undefined,
				originalHeight: undefined,
				lineCount2: 0,
				lineCount: 0,
				fromTab: 1, //判断是从【待办，已办】哪个tab页面进行的跳转  待办中跳转都能进行审批，已办只能查看详情
				detailId: undefined,
				loading: false,
				// 数据获取完进行附件展示
				hasLoad: false,
				// 基本信息
				mapData: [{
						name: '评审单号',
						label: 'reviewCode'
					},
					{
						name: '公司名称',
						label: 'companyName'
					},
					{
						name: '年度',
						label: 'year'
					},
					{
						name: '月份',
						label: 'month'
					},
				], //基本信息
				mapData2: [{
						name: '上期止账面借款',
						label: 'sqzzmjk'
					},
					{
						name: '本期应归还借款',
						label: 'bqyghjk'
					},
					{
						name: '本期应增加借款',
						label: 'bqyzjjk'
					},
					{
						name: '收款即还贷款还款额（元）',
						label: 'bqzljjk'
					},
					{
						name: '本期止累计借款',
						label: 'bqzljjk'
					},
					{
						name: '借款利率',
						label: 'jkll'
					},
					{
						name: '借款应计息',
						label: 'jkyjx'
					},
				], // 资金费用
				mapData3: [{
						name: '期初现金余额',
						label: 'value0'
					},
					{
						name: '其中：不可动用',
						label: 'value1'
					},
					{
						name: '现金收入',
						label: 'value2'
					},
					{
						name: '工程款收入',
						label: 'value3'
					},
					{
						name: '其它收入',
						label: 'value4'
					},
					{
						name: '现金支出',
						label: 'value5'
					},
					{
						name: '项目直接费',
						label: 'value6'
					},
					{
						name: '其中:项目间接费',
						label: 'value7'
					},
					{
						name: '其中:上交预收益',
						label: 'value8'
					},
					{
						name: '其中:归还公司借款',
						label: 'value9'
					},
					{
						name: '票据到期兑付支出',
						label: 'value10'
					},
					{
						name: '各类保证金',
						label: 'value11'
					},
					{
						name: '其他支出',
						label: 'value12'
					},
					{
						name: '期末现金余额（借款前）',
						label: 'value13'
					},
					{
						name: '公司借款流入',
						label: 'value14'
					},
					{
						name: '期末现金余额（借款后）',
						label: 'value15'
					},
					{
						name: '其中：不可动用部分',
						label: 'value16'
					},
				], // 资金计划
				formData: {},
				listData: [
					[],
					[]
				], //分包支出、分供支出列表
				// 分包支出、分供支出
				column: [{
					label: '合同名称',
				}, {
					label: '分包名称',
					key: 'subcontractor'
				}, {
					label: '分供名称',
					key: 'subsupplier'
				}, {
					label: '合同类型',
					key: 'contractTypeLabel'
				}, {
					label: '付款状态',
					key: 'payStatusLabel'
				}, {
					label: '本期应付款',
					key: 'bqyfk'
				}, {
					label: '计划金额',
					key: 'planMoney'
				}, {
					label: '支付方式',
					key: 'payMethod'
				}],
				// 资金费用
				expensesForm: {},
				// 资金计划
				planList: [],
				expensesPlan: {},
				// 审批
				approvalForm: {
					type: "1",
					// 审批意见
					comment: '同意',
					// 退回节点key
					targetKey: "",
					// 任务id
					taskId: "",
					// 流程实例id
					instanceId: "",
					// 退回节点名称
					returnNodeName: ""
				},
				showPicker: false,
				returnsList: [],
				rules: {
					type: [{
						required: true,
						message: '请选择审批结果',
						trigger: ['blur', 'change'],
						validator: checkApprovalType
					}],
					comment: [{
						required: true,
						message: '请输入审批意见',
						trigger: ['change'],
						validator: checkApprovalComment
					}],
					targetKey: [{
						required: true,
						message: '请选择退回节点',
						trigger: ['blur', 'change'],
						validator: checkApprovalTargetKey
					}],
				},
				// 退回节点时所用参数
				// 审批记录
				approvalInfo: {},
				flowList: [],
				//获取节点信息
				stepActive: 1,
			}
		},
		async onLoad({
			id,
			fromTab,
			taskId
		}) {
			this.fromTab = fromTab
			this.detailId = id
			this.approvalForm.taskId = taskId
			await this.getInfoById(this.detailId)
			// this.setTeamInfo()
			await this.getApprovalRecords()
			if (this.fromTab == 0) {
				this.getReturnList()
			}
		},
		watch: {
			screenHeight(newHeight) {
				// 解决安卓底部固定部位被软键盘顶上去问题
				//监听屏幕高度变化  
				var f = document.getElementById("fixB")
				if (newHeight < this.originalHeight) {
					f.style.position = 'static';
				} else {
					f.style.position = 'fixed';
				}
			}
		},
		mounted() {
			//首次进入的原始高度
			const windowInfo = uni.getWindowInfo();
			this.originalHeight = windowInfo.windowHeight;
			uni.onWindowResize(this.watchResize);
		},
		methods: {
			handleLineChange(index, i, it, e) {
				if (index == 0) {
					let y = ['合同名称', '分包名称'].indexOf(it.label)
					console.log(it.label, i, index, '----', e.detail.lineCount, ['合同名称', '分包名称'].indexOf(it.label));
					this.linecList[i][y] = e.detail.lineCount
					console.log(this.linecList[i][y], '--i,y');
				} else {
					i
					this.linecList2[i][
						['合同名称', '分供名称'].indexOf(it.label)
					] = e.detail.lineCount
				}
			},
			//实时变化的窗口高度
			watchResize() {
				const windowInfo = uni.getWindowInfo();
				this.screenHeight = windowInfo.windowHeight;
			},
			lineChange(val) {
				this.lineCount = val.detail.lineCount
			},
			successMethod(msg) {
				uni.showToast({
					title: msg,
					icon: 'none',
					duration: 2000
				})
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 2000)
			},
			// 通过方法
			confirmComplete() {
				this.$api.postConfirmComplete(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			},
			// 退回方法
			confirmReturn() {
				this.$api.postConfirmReturn(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			},
			// 驳回方法
			confirmReject() {
				this.$api.getConfirmReject(this.approvalForm).then((res) => {
					if (res.code === 200) {
						this.successMethod(res.msg)
					}
				});
			}, // 提交审批
			submitForm() {
				this.$refs.approvalForm.validate().then(valid => {
					if (valid) {
						switch (this.approvalForm.type) {
							case 1:
							case "1":
								// 通过
								this.confirmComplete();
								break;
							case 2:
							case "2":
								// 退回
								this.confirmReturn();
								break;
							case 3:
							case "3":
								// 驳回
								this.confirmReject();
								break;

						}
					}
				})
			},
			// 退回节点选择
			confirmPicker(val) {
				this.approvalForm.returnNodeName = val.value[0].name
				this.approvalForm.targetKey = val.value[0].id
				this.showPicker = false
			},
			closePicker() {
				this.showPicker = false
			},
			nodeInputHandler() {
				this.showPicker = true
			},
			// 获取可退回节点
			getReturnList() {
				this.$api.getReturnList(this.approvalForm).then(res => {
					this.returnsList = []
					this.returnsList.push(res.data)
				})
			},
			groupChange(val) {
				this.approvalForm.type = val
				this.approvalForm.targetKey = ""
				this.approvalForm.returnNodeName = ""
				if (this.approvalForm.type == 3) {
					this.approvalForm.comment = '驳回'
					this.$refs.approvalForm.validate()
				} else if (this.approvalForm.type == 1) {
					this.approvalForm.comment = '同意'
					this.$refs.approvalForm.validate()
				} else {
					this.approvalForm.comment = ""
					// this.getReturnList()
				}
			},
			ifSubLabel(label) {
				return [
					"期初现金余额",
					"现金收入",
					"现金支出",
					"期末现金余额（借款前）",
					"期末现金余额（借款后）"
				].indexOf(label) != -1
			},
			setTeamInfo() {
				// 基本信息
				this.mapData = new Map();
				this.mapData.set('评审单号', 'reviewCode')
				this.mapData.set('公司名称', 'companyName')
				this.mapData.set('年度', 'year')
				this.mapData.set('月份', 'month')
				// 资金费用
				this.mapData2 = new Map();
				this.mapData2.set('上期止账面借款', 'sqzzmjk')
				this.mapData2.set('本期应归还借款', 'bqyghjk')
				this.mapData2.set('本期应增加借款', 'bqyzjjk')
				this.mapData2.set('收款即还贷款还款额（元）', 'skjhdkhde')
				this.mapData2.set('本期止累计借款', 'bqzljjk')
				this.mapData2.set('借款利率', 'jkll')
				this.mapData2.set('借款应计息', 'jkyjx')
				// 资金计划
				this.mapData3 = new Map();
				this.mapData3.set('期初现金余额', 'value0')
				this.mapData3.set('其中：不可动用', 'value1')
				this.mapData3.set('现金收入', 'value2')
				this.mapData3.set('工程款收入', 'value3')
				this.mapData3.set('其它收入', 'value4')
				this.mapData3.set('现金支出', 'value5')
				this.mapData3.set('项目直接费', 'value6')
				this.mapData3.set('其中:项目间接费', 'value7')
				this.mapData3.set('其中:上交预收益', 'value8')
				this.mapData3.set('其中:归还公司借款', 'value9')
				this.mapData3.set('票据到期兑付支出', 'value10')
				this.mapData3.set('各类保证金', 'value11')
				this.mapData3.set('其他支出', 'value12')
				this.mapData3.set('期末现金余额（借款前）', 'value13')
				this.mapData3.set('公司借款流入', 'value14')
				this.mapData3.set('期末现金余额（借款后）', 'value15')
				this.mapData3.set('其中：不可动用部分', 'value16')
			},
			// 获取节点信息
			getApprovalNode(procInsId) {
				this.$definition.getApprovalNode(procInsId).then((res) => {
					if (res.code === 200) {
						this.stepActive = res.data.active
					}
				});
			},
			async getInfoById(id) {
				await this.$api.getFundInfoById(id).then(res => {
					this.approvalInfo = res.data.approvalInfo
					//获取节点信息
					this.getApprovalNode(this.approvalInfo.procInsId)
					this.formData = res.data.pdFundPlanBase
					this.expensesForm = res.data.pdFundPlanCost
					this.planList = res.data.pdFundPlanLists.filter(it => {
						return [
							"期初现金余额",
							"其中：不可动用",
							"现金收入",
							"工程款收入",
							"其他收入",
							"现金支出",
							"项目直接费",
							"其中：项目间接费",
							"其中：上交预收益",
							"其中：归还公司借款",
							"票据到期兑付支出",
							"各类保证金",
							"其他支出",
							"期末现金余额（借款前）",
							"公司借款流入",
							"期末现金余额（借款后）",
							"其中：不可动用部分",
						].indexOf(it.item) != -1
					})
					this.expensesPlan = {}
					let values = this.planList.map(item => {
						return item.currentPlan
					})
					values.forEach((v, i) => {
						this.expensesPlan[`value${i}`] = v
					})
					this.listData[0] = [...res.data.pdFundPlanSubcontractorDtoList] ? [...res.data
							.pdFundPlanSubcontractorDtoList
						] : [],
						this.linecList = [
							...Array(this.listData[0].length).fill([])
						]
					this.linecList.forEach((it, i) => {
						it = [...Array(2).fill(0)]
					})
					this.listData[1] = res.data.pdFundPlanSubsupplierDtoList.length ? [...res.data
							.pdFundPlanSubsupplierDtoList
						] : [],

						this.linecList2 = [
							...Array(this.listData[1].length).fill([])
						]
					this.linecList2.forEach((it, i) => {
						it = [...Array(2).fill(0)]
					})
				})
			},
			// 获取审批记录
			async getApprovalRecords() {
				let param = {
					procInsId: this.approvalInfo.procInsId,
					deployId: this.approvalInfo.deployId,
				};
				await this.$api.getApprovalRecords(param).then(res => {
					this.flowList = [...res.data.flowList]
					this.flowList = this.flowList.reverse()
					// this.approvalForm.taskId = res.data.flowList[0]?.taskId
					this.approvalForm.instanceId = this.approvalInfo.procInsId;
				})
				this.pageLoading = false
			},
		},
	}
</script>

<style lang="scss" scoped>
	.container-box {
		margin-top: 18rpx;
		padding-bottom: 160rpx;
	}

	.space {
		@include center-space()
	}

	.group-text ::v-deep uni-text.u-radio__text {
		font-size: 28rpx !important;
	}

	.approval-box {
		border-bottom: 1px solid #dee2eb;
		@include center();

		.approval-info {
			width: 600rpx;
		}

		.line-user {
			color: #B1B3B7;
			position: relative;
		}
	}

	.fs-28 {
		@include text-font-size(28rpx)
	}


	.fix-btn {
		position: fixed;
		background-color: #fff;
		width: 100%;
		height: 160rpx;
		bottom: 0;

		::v-deep .u-button {
			margin: 34rpx auto;
			width: 694rpx;
			height: 92rpx;
			font-size: 28rpx;
		}
	}

	.approval-form {
		::v-deep .u-form-item__body {
			padding-top: 0;
		}

		::v-deep .u-form-item__body__right__message {
			margin-left: 0 !important;
		}
	}

	/* 折叠面板 */
	.collapse-box {
		::v-deep .u-cell {
			border-bottom: 2rpx solid #dee2eb;
		}

		::v-deep .u-cell__title-text,
		::v-deep .u-page__item__title__slot-title {
			font-size: 28rpx
		}

		::v-deep .u-collapse-item {
			border: 1px solid #dee2eb;
			border-radius: 8rpx;
		}

		::v-deep .u-collapse-item__content__text {
			padding-top: 0;
			padding-bottom: 0;
		}
	}

	.sub-label {
		::v-deep uni-text.u-form-item__body__left__content__label {
			font-weight: bold;
			font-size: 29rpx !important;
		}
	}

	.radio-flex,
	.uni-list-cell {
		display: flex;
	}

	.radio-flex {
		::v-deep uni-radio .uni-radio-input {
			width: 20px;
			height: 20px;
		}

		.uni-list-cell {
			margin-right: 10rpx;
		}
	}
</style>